;
(function () {
  Array.prototype.removeRepeatBuildingAndFLoor = function () {
    var res = [this[0]];
    for (var i = 1; i < this.length; i++) {
      var repeat = false;
      for (var j = 0; j < res.length; j++) {
        if (this[i].buildingName == res[j].buildingName && this[i].floorNum == res[j].floorNum) {
          repeat = true;
        }
      }
      if (!repeat) {
        res.push(this[i]);
      }
    }
    return res;
  };

  new Vue({
    el: '#contract-detail',
    data: {
      tenantId: JSON.parse(window.localStorage.getItem('userMes')).tenantId,
      tenantIds: ['105', '74', '68', '86', '107', '103', '275', '88', '15', '2', '48', '96', '37', '100', '30', '64', '1', '11', '83'],
      tabData: [{
          'name': '合同信息'
        },
        {
          'name': '账单信息'
        },
        // { 'name': '凭证列表', 'privilege': 'c323' },
        // { 'name': '收入确认', 'privilege': 'c322' },
        // { 'name': '相关文件' },
        // { 'name': '历史版本' },
      ],
      tabSelectedIndex: 0,
      contract: {
        commissionRules: [],
        expenses: []
      }, // 合同信息
      withdraw: {}, // 退租信息
      resourceMes: {
        st: [],
        ot: []
      }, // 资源信息
      contractAuditState: '', // 合同状态
      withdrawAuditState: '', // 退租单状态
      building: [], // 楼宇数据
      totalArea: 0,
      st: [], // 车位
      wp: [], // 工位
      stTotalNum: 0, // 车位总数量
      wpTotalNum: 0, // 工位总数量
      isShowUnit: false,
      freeDate: [], // 免租期
      rent: [], // 租金
      rentPriceUnit: 'D', // 租金单位
      pExpense: [], // 周期性费用
      oExpense: [], // 一次性费用
      tExpense: [], // 临时性费用
      contractFile: [], // 合同文件
      selectedTabItem: '合同信息',
      loadContractMesModule: true,
      loadBillMesModule: false,
      loadFileMesModule: false,
      loadVoucherModule: false,
      loadIncomeModule: false,
      loadHistoryModule: false,
      permissions: JSON.parse(window.localStorage.getItem('permissions')),
      contractId: hlUrlUtil.GetQueryString('id'),
      contractType: hlUrlUtil.GetQueryString('type'), //合同操作类型（终止）
      pageFrom: hlUrlUtil.GetQueryString('page'), //合同操作类型（终止）
      version: hlUrlUtil.GetQueryString('version'),
      isShowSubmitLayer: false,
      submitLayerData: {
        companyName: '',
        beginDate: '',
        endDate: '',
        id: ''
      },
      billParams: {
        contract_id: hlUrlUtil.GetQueryString('id')
      },
      oldBillParams: {
        history_contract_id: hlUrlUtil.GetQueryString('historyContractId')
      },
      alterId: hlUrlUtil.GetQueryString('alterId'),
      delFlag: false,
      unitId: null, // 单元id
      unitDetailsFlag: false,
      industryTypes: {
        list: []
      },
      history: [],
      showCreateBill: false,
      TemTypeList: ['Word', 'PDF'],
      selectedTemTypeList: [],
      temList: [],
      selectedTemList: '',
      TemplateModulShow: false,
      progress: '',
      terminationReasonList: [], //终止原因
      selectTerminationReasonCode: '',
      TerminationReasonIns: '',
      contractIncomeData: {},
      voucherList: [],
      projectId: '',
      isGDZJflag: false,
      isYJflag: false,
      billUrl: null,
      tmpData: []
    },
    filters: {
      formatDate: function (time) {
        if (time === undefined) return '--'
        return hlDateUtil.formatUTCDate(time, 'yyyy-MM-dd')
      },
      formatDetailDate: function (time) {
        if (time === undefined) return '--'
        return hlDateUtil.formatUTCDate(time)
      },
      formatUndefined: function (item) {
        if (!item) return '--'
        return item
      },
      formatIndustry: function (item) {
        return hlCodeConvert.industryType(item)
      },
      formatZlfType: function (item) {
        return hlCodeConvert.contractZlfType(item)
      },
      formatContractType: function (item) {
        return hlCodeConvert.contractType(item)
      },
      formatContractAuditState: function (item) {
        return hlCodeConvert.contractAuditState(item)
      },
      formatNum: function (item) {
        return hlNumberUtil.formatNum(item)
      }
    },
    computed: {
      ityName: function () {
        var result;
        var self = this;
        this.industryTypes.list.map(function (item) {
          if (self.contract.zlfIndustryType == item.dictCode) {
            result = item.dictName;
          }
        })
        return result;
      },
      monthArr() {
        let arr = [];
        let number = 12;
        for (let i = 1; i <= number; i++) {
          arr.push(i)
        }
        return arr
      },
      yearArr() {
        let year = new Date().getFullYear();
        let arr = [year + 1, year, year - 1];
        return arr;
      },
      yaTotal() {
        let num = 0
        this.contract.expenses.map(item => {
          if (item.expenseType == 'D') {
            num = num + Number(item.amount)
          }
        })
        return num.toFixed(2)
      }
    },
    methods: {
      //合同退租校验
      checkWithout() {
        var that = this
        hlhttp.get({
          url: 'withdraw/_check',
          data: {
            'contract_id': this.contractId
          },
          success: function (res) {
            hlUrlUtil.goTo('withdrawAudit', {
              ddtab: true,
              contractId: that.contractId
            }, true)
          },
        })
      },
      // :href="'#/contractNewDeatil?version='+ item.version + '&ddtab=true&id=' + contractId"
      historyContract(item) {
        let data = {};
        if (item.alterId) {
          data = {
            version: item.version,
            id: item.contractId,
            alterId: item.alterId,
            historyContractId: item.historyContractId,
            'ddtab': true,
          }
        } else {
          data = {
            version: item.version,
            id: item.contractId,
            'ddtab': true,
          }
        }
        hlUrlUtil.goTo('contractNewDeatil', data, true)
      },
      exportContrat() {
        hlhttp.get({
          baseUrl: exclUrl,
          url: 'resource/contract/revenue_recognitions/_export',
          data: {
            "contract_id": this.contractId || '#',
          },
          success: function (res) {
            window.open(res.url)
          }
        })
      },
      // 前往凭证详情
      goToDetail(id, item) {
        hlUrlUtil.goTo('voucherDetail', {
          'ddtab': true,
          'id': id,
          date: item.voucherDate
        }, true)
      },
      // 获取财务凭证列表
      getVoucherList() {
        var that = this
        hlhttp.get({
          url: 'acct/contract/vouchers',
          data: {
            "contract_id": this.contractId
          },
          success: function (res) {
            that.voucherList = res
          }
        })
      },
      //合同收入确认详情
      contractIncomeDt() {
        hlhttp.get({
          url: 'contract/revenue_recognition',
          data: {
            contract_id: this.contractId
          },
          success: (data) => {
            let monthArr = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
            let yearMonthArr = [];
            if (!data.year) return;
            data.year.map(item => {
              monthArr.map(item0 => {
                yearMonthArr.push({
                  month: item + '-' + item0,
                  amount: '--'
                })
              })
            })

            data.revenueRecognitions.map(item => {
              let arr = hlArrayUtil.diffent(item.amounts, yearMonthArr, 'month');
              item.amounts = arr.concat(item.amounts)
              item.amounts.map(item1 => {
                item1.index = item1.month.replace('-', '')
              })
              item.amounts = item.amounts.sort(hlArrayUtil.compareAsc('index'))
            })

            this.contractIncomeData = data
          }
        })
      },
      //选择关闭理由
      selectTerminationReason(code) {
        this.selectTerminationReasonCode = code
      },
      //获取终止原因
      getTerminationReason() {
        var that = this
        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'HETN',
            config_name: 'HT_TERMINATION_REASON',
          },
          success: function (res) {
            that.terminationReasonList = res
          }
        })
      },
      //合同终止校验
      checkClose(val) {
        var that = this
        hlhttp.get({
          url: 'contract/_close/_check',
          data: {
            'contract_id': this.contractId
          },
          success: function (res) {
            that.sureContractEnd()
          },
        })
      },
      //确认终止合同
      sureContractEnd() {
        if (!this.selectTerminationReasonCode) {
          hl.toast('请选中关闭原因')
          return
        }
        var that = this
        hlhttp.put({
          url: 'contract/_close',
          data: {
            contract_id: this.contractId,
            termination_reason_code: this.selectTerminationReasonCode,
            termination_desc: this.TerminationReasonIns || '#',
          },
          success: function (res) {
            if (that.pageFrom == 'unitContractList') {
              hlUrlUtil.goTo('unitContractList', {
                ddtab: true
              }, false)
            } else {
              hlUrlUtil.goTo('wpContractList', {
                ddtab: true
              }, false)
            }
          }
        })
      },
      //预览合同模板
      preview(id) {
        let free_dates = []
        let data = {
          rent_way: this.contract.rentWay + '' || '#',
          period: this.contract.paymentPeriod + '' || '#',
          rent_late_fee_percent: this.contract.rentLateFeePercent || '#',
          rent_increse_days: this.contract.rentIncreseDay || '#',
          rent_increse_months: this.contract.rentIncreseMonth || '#',
          rent_increse_dates: this.contract.rentIncreseDate || '#',
          begin_date: hlDateUtil.formatUTCDate(this.contract.beginDate, 'yyyy-MM-dd'),
          first_payment_date: hlDateUtil.formatUTCDate(this.contract.firstPaymentDate, 'yyyy-MM-dd'),
          bill_date_BOA: this.contract.billDateBOA || '#',
          bill_date_fix_type: this.contract.billDateFixType || '#',
          bill_date_fix_num: this.contract.billDateFixNum + '' || '#',
          rent_increase_way: this.contract.rentIncreaseWay + ''
        }
        this.contract.freeDates.map(item => {
          free_dates.push({
            free_begin_date: hlDateUtil.formatUTCDate(item.freeBeginDate, 'yyyy-MM-dd'),
            free_end_date: hlDateUtil.formatUTCDate(item.freeEndDate, 'yyyy-MM-dd'),
            bill_hidden_flag: item.billHiddenFlag
          })
        })
        data.free_dates = free_dates.length ? free_dates : '#'
        let expenses = []
        this.contract.expenses.map(item => {
          item.customPeriod.map(item1 => {
            item1.begin_date = hlDateUtil.formatUTCDate(item1.beginDate, 'yyyy-MM-dd')
            item1.end_date = hlDateUtil.formatUTCDate(item1.endDate, 'yyyy-MM-dd')
          })
        })
        this.contract.expenses.map(item => {
          expenses.push({
            "name": item.expenseName,
            "period": item.expensePeriod ? item.expensePeriod : '#',
            "amount": item.amount ? item.amount : '#',
            "price": item.price ? item.price : '#',
            "priceDay": item.priceDay ? item.priceDay : '#',
            "priceMonth": item.priceMonth ? item.priceMonth : '#',
            "late_fee_percent": item.lateFee ? item.lateFee : '#',
            "expense_type": item.expenseType ? item.expenseType : '#',
            "custom_period": item.customPeriod ? item.customPeriod : '#',
            "units_code": '#',
            "units_val": '#',
            "payment_date_config": "#",
            "commission_date_boa": "#",
            "commission_date_fix_type": "#",
            "commission_date_fix_num": "#",
            "tax_percent": item.taxPercent ? item.taxPercent : '#'
          })
        })
        hlhttp.get({
          baseUrl: exclUrl,
          url: 'resource/contract_content_tempalte_preview',
          data: {
            template_id: id,
            contract_id: this.contractId,
            contract_info: '#',
            contract: JSON.stringify(data),
            expenses: JSON.stringify(expenses)
          },
          success: function (data) {
            $.previewPDF(data.pdf_url)
          }
        })
      },
      //导出合同模板
      exportTemplate() {
        if (!this.selectedTemTypeList.length) {
          hl.toast('请选择文件类型')
          return
        }
        if (!this.selectedTemList) {
          hl.toast('请选择模板')
          return
        }
        var that = this

        hlhttp.get({
          baseUrl: exclUrl,
          url: 'resource/contract_export',
          data: {
            contract_id: that.contractId,
            template_id: that.selectedTemList,
            file_type: that.selectedTemTypeList.join(',')
          },
          success: function (data) {
            that.downloadFiles(data)
            that.TemplateModulShow = false
          }
        })
      },
      createIFrame(url) {
        setTimeout(() => {
          let frame = document.createElement('iframe');
          frame.style = 'display: none;';
          frame.class = 'multi-download';
          frame.src = url,

            document.body.appendChild(frame);
          setTimeout(function () {
            document.body.removeChild(frame);
          }, 1000);

        })
      },
      downloadFiles(fileUrls) {
        fileUrls.forEach(v => {
          this.createIFrame(v);
        })
      },
      //新增合同模板
      addNewTem() {
        hlUrlUtil.goTo('billTemplate', {
          ddtab: true
        }, true)
      },
      //合同预览/打印
      previewTemPrint() {
        this.TemplateModulShow = true

        var that = this
        hlhttp.get({
          url: 'contract/print_templates',
          success: function (data) {
            that.temList = data
          }
        })
      },
      //选择文档类型
      selectedTemType(item) {
        let index = this.selectedTemTypeList.indexOf(item)
        if (index > -1) {
          this.selectedTemTypeList.splice(index, 1)
        } else {
          this.selectedTemTypeList.push(item)
        }
      },
      //选择文档
      selectedTem(item) {
        this.selectedTemList = item.id
      },
      createRelet() {
        hlUrlUtil.goTo('contractNew1', {
          ddtab: true,
          relet: true,
          id: this.contractId,
          m_code: this.contract.mCode
        }, false)
      },
      //获取行业列表
      getindustryTypes() {
        var _this = this;
        hlhttp.get({
          url: 'configure/industry/dict',
          success: function (data) {
            _this.industryTypes.list = data;
          }
        })
      },
      //删除合同
      delContract() {
        var _this = this;
        hlhttp.delete({
          url: 'contract?contract_id=' + _this.contractId,
          success: function () {
            _this.delFlag = false;
            hl.toast('删除成功')
            hlUrlUtil.goTo('unitContractList', {
              'ddtab': true
            }, false)
          }
        })
      },
      handleSelectedTab: function (val, i) {
        const {
          name,
          isDisabled
        } = val

        if (name == '合同信息') {
          this.loadContractMesModule = true;
          this.loadBillMesModule = false;
          this.loadFileMesModule = false;
          this.loadHistoryModule = false;
          this.loadIncomeModule = false;
          this.loadVoucherModule = false;
          this.tabSelectedIndex = 0
          return false
        }
        if (name == '账单信息') {
          this.loadContractMesModule = false;
          this.loadBillMesModule = true;
          this.loadFileMesModule = false;
          this.loadHistoryModule = false;
          this.loadIncomeModule = false;
          this.loadVoucherModule = false;
          this.tabSelectedIndex = 1
          // 获取账单信息
          this.fetchContractBillData()
          return false
        }
        if (name == '凭证列表') {
          this.loadContractMesModule = false;
          this.loadBillMesModule = false;
          this.loadFileMesModule = false;
          this.loadHistoryModule = false;
          this.loadIncomeModule = false;
          this.loadVoucherModule = true;
          this.tabSelectedIndex = 2
          return false
        }
        if (name == '收入确认') {
          this.loadContractMesModule = false;
          this.loadBillMesModule = false;
          this.loadFileMesModule = false;
          this.loadHistoryModule = false;
          this.loadIncomeModule = true;
          this.loadVoucherModule = false;
          this.tabSelectedIndex = 3
          return false
        }
        if (name == '相关文件') {
          this.loadContractMesModule = false;
          this.loadBillMesModule = false;
          this.loadFileMesModule = true;
          this.loadHistoryModule = false;
          this.loadIncomeModule = false;
          this.loadVoucherModule = false;
          this.tabSelectedIndex = 4
          return false
        }
        if (name == '历史版本') {
          this.loadContractMesModule = false;
          this.loadBillMesModule = false;
          this.loadFileMesModule = false;
          this.loadHistoryModule = true;
          this.loadIncomeModule = false;
          this.loadVoucherModule = false;
          this.tabSelectedIndex = 5
          return false
        }


      },
      // 获取合同详情数据
      fetchContractDetailData: function () {
        var self = this;
        var data = {}

        hlhttp.get({
          url: 'contract',
          data: {
            id: self.contractId,
            version: self.version
          },
          success: function (data) {
            console.log(this)
            console.log(self)

            self.tmpData = data.pageCustomizeComponentBizContentList ? data.pageCustomizeComponentBizContentList : []

            if (data.customConfigProperty) {
              data.customConfigProperty = JSON.parse(data.customConfigProperty)
            }
            if (data.expenses.length) {
              data.expenses.some(item => {
                if (item.expenseType == 'R') {
                  self.isGDZJflag = true
                }
              })
              data.expenses.some(item => {
                if (item.expenseType == 'D') {
                  self.isYJflag = true
                }
              })
            } else {
              self.isGDZJflag = true
            }

            loginPrem.loginList()
            self.$set(self.$data, 'contract', data)
            self.contractAuditState = data.auditState;
            self.contractId = data.id;
            self.projectId = data.projectId;
            if (self.permissions.indexOf('c323') != -1) {
              self.getVoucherList();
            }

            if (data.contractType === 'WR') {
              self.isShowUnit = false;
            } else {
              self.isShowUnit = true;
            }

            if (data.auditState == 'EX' || data.auditState == 'FN' || data.auditState == 'EN') {
              self.showCreateBill = true
            }

            if (data.rentPriceUnit === 'D' && data.contractType === 'ER') {
              self.rentPriceUnit = 'DM'
            }
            if (data.rentPriceUnit === 'M' && data.contractType === 'ER') {
              self.rentPriceUnit = 'MM'
            }
            if (data.rentPriceUnit === 'D' && data.contractType === 'WR') {
              self.rentPriceUnit = 'DG'
            }
            if (data.rentPriceUnit === 'M' && data.contractType === 'WR') {
              self.rentPriceUnit = 'MG'
            }

            // 单元
            var buildingData = self.unitData(data.units)
            self.totalArea = data.rentAcreage
            self.building = buildingData.building
            // 车位
            self.st = [];
            self.wp = [];
            var stTotalNum = 0;
            var wpTotalNum = 0;
            data.units.map(function (item) {
              if (item.positions && item.unitType === 'ST') {
                stTotalNum = stTotalNum + item.positions.length;
                item['num'] = item.positions.length;
                self.st.push(item)
              }
              if (item.positions && item.unitType === 'WP') {
                wpTotalNum = wpTotalNum + item.positions.length;
                item['num'] = item.positions.length;
                self.wp.push(item)
              }
            })
            self.stTotalNum = stTotalNum;
            self.wpTotalNum = wpTotalNum;
            if (!data.commissionRules) {
              data.commissionRules = []
            }
            // 租金数据
            self.rent = [];
            if (data.rentIncreseDate && data.rentIncreseDate.split(',').length > 1) {
              for (var i = 1; i < data.rentIncreseDate.split(',').length; i++) {
                self.rent.push({
                  beginDate: data.rentIncreseDate.split(',')[i],
                  percent: data.rentIncresePercent.split(',')[i] ? data.rentIncresePercent.split(',')[i] : '',
                  price: data.rentIncresePrice ? data.rentIncresePrice.split(',')[i] : '',
                  dayPrice: data.rentIncreseDay ? data.rentIncreseDay.split(',')[i] : '',
                  monthPrice: data.rentIncreseMonth ? data.rentIncreseMonth.split(',')[i] : '',
                  discount: data.rentIncreseMonth ? data.rentIncreseMonth.split(',')[i] : '',
                  discountD: data.rentIncreseMonth ? data.rentIncreseMonth.split(',')[i] : '',
                  discountM: data.rentIncreseMonth ? data.rentIncreseMonth.split(',')[i] : ''
                })
              }
            }
            // 折扣月租金
            if (data.rentIncreseDiscountDay) {
              let arr1 = data.rentIncreseDiscountRate.split(',')
              let arr2 = data.rentIncreseDiscountDay.split(',')
              let arr3 = data.rentIncreseDiscountMonth.split(',')
              self.rent.map((item, index) => {
                item.discount = arr1[index + 1]
                item.discountD = arr2[index + 1]
                item.discountM = arr3[index + 1]
              })
            }

            // 合同免租期
            self.freeDate = [];
            if (data.freeDates) {
              // for (var m = 0; m < data.freeDate.split(',').length; m++) {
              //   self.freeDate.push({
              //     beginDate: data.freeDate.split(',')[m].split('~')[0],
              //     endDate: data.freeDate.split(',')[m].split('~')[1]
              //   })
              // }
              self.freeDate = data.freeDates
            }
            // 费用数据
            self.pExpense = [];
            self.oExpense = [];
            self.tExpense = [];
            if (data.expenses) {
              for (var j = 0; j < data.expenses.length; j++) {
                if (data.expenses[j].expenseType == 'P') {
                  self.pExpense.push(data.expenses[j])
                }
                if (data.expenses[j].expenseType == 'O') {
                  self.oExpense.push(data.expenses[j])
                }
                if (data.expenses[j].expenseType == 'T') {
                  self.tExpense.push(data.expenses[j])
                }
              }
            }
            // 合同文件数据
            if (data.attachmentNames) {
              for (var k = 0; k < data.attachmentNames.length; k++) {
                var fileObj = {
                  name: data.attachmentNames[k],
                  url: data.attachmentUrls[k]
                }
                self.contractFile.push(fileObj)
              }
            }
            // 合同版本号 当合同版本号大于1时 才显示历史版本tab项
            if (data.version > 1) {
              self.tab.push('历史版本')
            }
          }
        })
      },
      // 获取合同账单数据
      fetchContractBillData: function () {
        // progress.init(this.contractId)
      },
      // 获取合同退租详情数据
      fetchWithdrawDetailData: function () {
        var self = this;
        hlhttp.get({
          url: 'contract/withdraw',
          data: {
            contract_id: self.contractId
          },
          success: function (res) {
            self.withdraw = res;
          }
        })
      },
      // 上传文件
      uploadFile: function () {
        if (this.progress) {
          hl.toast('文件尚未上传完成')
          return
        }
        $('.upload-filess').trigger('click')
      },
      fileUpload: function () {
        var that = this;
        fileUpload('.upload-filess', uploadUrl, function (src) {
          if (src.json == undefined) return
          that.progress = ''
          hlhttp.post({
            url: 'contract_attachment',
            data: {
              contract_id: that.contractId,
              attachment_names: src.json.name,
              attachment_url: src.json.url
            },
            success: function () {
              hl.toast('上传成功')
              that.contractFile.push({
                name: src.json.name,
                url: src.json.url
              })
            }
          })
        }, function (val) {
          that.progress = parseInt((val.loaded / val.total) * 100) + '%'
        })
      },
      // 删除文件
      deleteFile: function (val, i) {
        var self = this;
        hlhttp.delete({
          url: 'contract_attachment?contract_id=' + self.contractId + '&attachment_url=' + val,
          success: function () {
            hl.toast('删除成功')
            self.contractFile.splice(i, 1)
          }
        })
      },
      // 编辑合同
      editContract: function () {
        // 清除合同编辑中上一步及下一步存储的本地信息
        var arr = [
          'CREATED_CONTRACT_FIRST_STEP',
          'CREATED_CONTRACT_SECOND_STEP'
        ]
        hlStorage.ssClearMultipleKey(arr)

        if (this.contract.renewFlag == 'Y') {
          hlUrlUtil.goTo('contractNew1', {
            id: this.contractId,
            relet: true,
            ddtab: true
          })
        }
        hlUrlUtil.goTo('contractNew1', {
          id: this.contractId,
          ddtab: true
        })
      },
      // 作废合同
      invalidContract: function () {
        var self = this;
        hllayer.confirm1('此操作不可逆转，确认作废合同吗？', function () {
          hlhttp.put({
            url: 'contract/_cancel',
            data: {
              "id": self.contractId,
              "project_id": self.projectId
            },
            success: function (data) {
              self.fetchContractDetailData()
            }
          })
        })
      },
      // 提交合同
      submitContract: function () {
        var self = this;
        hlhttp.put({
          url: 'bpm/check_project_use',
          data: {
            bpm_key: 'CT',
            project_id: self.projectId
          },
          success: function (res) {
            if (res.flag == 'N') {
              hl.toast('请先配置流程')
              return
            }
            self.isShowSubmitLayer = true;
          }
        })
      },
      // 确认提交合同
      confirmSubmitContract: function () {
        var self = this;
        self.isShowSubmitLayer = false;
        hlhttp.put({
          url: 'contract/wa',
          data: {
            contract_id: self.contractId
          },
          success: function (data) {
            self.isShowSubmitLayer = false;
            self.fetchContractDetailData()
          }
        })
      },
      closeSubmitLayer: function () {
        this.isShowSubmitLayer = false;
      },
      unitData: function (unitsData) {
        // 去除含有工位车位的单元
        var units = [];
        unitsData.map(function (_item) {
          if (_item.positions.length === 0) {
            units.push(_item)
          }
        })
        if (units.length === 0) {
          return {
            building: [],
            totalArea: 0
          }
        }
        // 合并单元项
        var unit = [];
        var totalArea = 0;
        for (var i = 0; i < units.length; i++) {
          unit.push({
            buildingName: units[i].buildingName,
            floorNum: units[i].floorNum,
            floorName: units[i].floorName,
            unit: [],
            unitId: []
          })
        }
        var unitArr = unit.removeRepeatBuildingAndFLoor()
        for (var z = 0; z < unitArr.length; z++) {
          for (var m = 0; m < units.length; m++) {
            if (units[m].buildingName == unitArr[z].buildingName && units[m].floorNum == unitArr[z].floorNum) {
              unitArr[z].unit.push(units[m].unitName + '(' + hlNumberUtil.formatNum(units[m].unitAcreage) + 'm²)')
              unitArr[z].unitId.push(units[m].unitId)
              totalArea = totalArea + Number(units[m].unitAcreage)
            }
          }
        }
        // 合并楼层项
        var building = [];
        for (var j = 0; j < unitArr.length; j++) {
          building.push({
            buildingName: unitArr[j].buildingName,
            floor: []
          })
        }
        var buildingArr = hlArrayUtil.removeRepeat(building, 'buildingName')
        for (var k = 0; k < buildingArr.length; k++) {
          for (var n = 0; n < unitArr.length; n++) {
            if (unitArr[n].buildingName == buildingArr[k].buildingName) {
              buildingArr[k].floor.push({
                'floorNum': unitArr[n].floorNum,
                'floorName': unitArr[n].floorName,
                'unit': unitArr[n].unit,
                'unitId': unitArr[n].unitId
              })
            }
          }
        }
        return {
          building: buildingArr,
          totalArea: totalArea
        }
      },
      // 获取单元详情
      getUnitDetails: function (unitId) {
        var self = this;
        self.unitId = unitId;
        self.unitDetailsFlag = true;
      },
      closeUnitPop: function (state) {
        this.unitId = null;
        this.unitDetailsFlag = false;
      },
      previewImage: function (url) {
        var imageExt = ['jpg', 'jpeg', 'png', 'JPG', 'JPEG', 'PNG'];
        var pdfExt = ['pdf', 'PDF'];
        var officeExt = ['docx', 'doc', 'xlsx', 'xls', 'xlt']
        var imageFlag = false;
        var pdfFlag = false;
        var officeFlag = false;

        imageExt.forEach((e, i) => {
          if (url.indexOf(e) !== -1) imageFlag = true;
        })

        if (imageFlag) {
          $.imageShow([url])
          return
        }
        pdfExt.forEach((e, i) => {
          if (url.indexOf(e) !== -1) pdfFlag = true;
        })
        if (pdfFlag) {
          $.previewPDF(url)
          return
        }

        officeExt.forEach((e, i) => {
          if (url.indexOf(e) !== -1) officeFlag = true
        })
        if (officeFlag) {
          $.previewOffice(url)
          return
        }
        hl.toast('暂不支持该格式')
      },
      // 获取历史版本信息
      getHistory: function () {
        var self = this;
        hlhttp.get({
          url: 'contract_alter/history',
          data: {
            'contract_id': self.contractId
          },
          success: function (data) {
            self.history = data.alterHistory;
            if (!data.alterHistory.length) {
              if (self.alterId) {
                self.tabData = [{
                    'name': '合同信息'
                  },
                  {
                    'name': '账单信息'
                  },
                  // { 'name': '凭证列表', 'privilege': 'c323' },
                  // { 'name': '收入确认', 'privilege': 'c322' },
                  {
                    'name': '相关文件'
                  },
                  // { 'name': '历史版本' },
                ]
              }
              if (!self.alterId) {
                self.tabData = [{
                    'name': '合同信息'
                  },
                  {
                    'name': '账单信息'
                  },
                  {
                    'name': '凭证列表',
                    'privilege': 'c323'
                  },
                  {
                    'name': '收入确认',
                    'privilege': 'c322'
                  },
                  {
                    'name': '相关文件',
                    'privilege': 'c126'
                  },
                  // { 'name': '历史版本' },
                ]
              }
            }
            if (data.alterHistory.length) {
              if (self.alterId) {
                self.tabData = [{
                    'name': '合同信息'
                  },
                  {
                    'name': '账单信息'
                  },
                  // { 'name': '凭证列表', 'privilege': 'c323' },
                  // { 'name': '收入确认', 'privilege': 'c322' },
                  {
                    'name': '相关文件',
                    'privilege': 'c126'
                  },
                  {
                    'name': '历史版本'
                  },
                ]
              }
              if (!self.alterId) {
                self.tabData = [{
                    'name': '合同信息'
                  },
                  {
                    'name': '账单信息'
                  },
                  {
                    'name': '凭证列表',
                    'privilege': 'c323'
                  },
                  {
                    'name': '收入确认',
                    'privilege': 'c322'
                  },
                  {
                    'name': '相关文件',
                    'privilege': 'c126'
                  },
                  {
                    'name': '历史版本'
                  },
                ]
              }
            }

          }
        })
      },
      updateContract: function () {
        var self = this;
        hlhttp.get({
          url: 'contract/alter_code',
          data: {
            'contract_id': self.contractId
          },
          success: function (data) {
            if (data.editFlag === 'true') {
              hlUrlUtil.goTo('contractUpdateDetails', {
                contractId: self.contractId,
                id: data.alterId,
                ddtab: true
              }, true)
            }

            if (data.editFlag === 'false') {
              hlUrlUtil.goTo('contractChangeIndex', {
                'id': self.contractId,
                'code': data.code,
                'ddtab': true
              }, true)
            }
          }
        })
      },
      createBill() {
        hlUrlUtil.goTo('createBill', {
          'page': 'billList',
          'ddtab': true,
          'code': this.contract.mCode,
          'type': 'HT',
          'name': escape(this.contract.zlfCompany),
          'HTname': escape(this.contract.name)
        })
      },
      confirmExportBill() {

      },
      exportBill() {
        console.log('22');
        var self = this;
        hlhttp.get({
          baseUrl: exclUrl,
          url: 'resource/bill_excel',
          data: {
            'contract_id': self.contractId
          },
          success: function (data) {
            console.log(data);
            self.billUrl = data.excel_url

            setTimeout(() => {
              document.getElementById('billLink').click();
            }, 1000)

          }
        })

      }
    },
    mounted: function () {
      this.uploadFile()
      this.fileUpload()
      this.getindustryTypes()
      this.fetchContractDetailData()
      this.getHistory()
      this.getTerminationReason()
      this.contractIncomeDt()


    }


  })
}())